﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CrystalDecisions.CrystalReports.Engine;
using System.Data.SqlClient;

namespace SchoolManagementSystem
{
    public partial class Murid : Form
    {
        private BindingSource bindingSource1 = new BindingSource();
        public DataTable dTable = null;
        private MuridAdd add = null;
        private MuridEdit edit = null;

        public Murid()
        {
            InitializeComponent();
            Style.setDatagridviewStyle(dataGridView1);
        }

        private void btnDaftar_Click(object sender, EventArgs e)
        {
            if (this.add==null || this.add.IsDisposed)
                add = new MuridAdd();

            //check whether the form has been opened or not
            if (((Main)this.MdiParent).isOpenForm(add))
            {
                add = null;
                return;
            }

            add.MdiParent = this.MdiParent;
            add.Show();
        }

        private void Murid_Load(object sender, EventArgs e)
        {
            this.update();
        }

        private void update()
        {
            this.update("select * from Student");
        }

        private void update(string sql)
        {
            this.dataGridView1.Columns.Clear();

            dTable = Database.getInstance().query(sql);

            // Get student status (terdaftar, mutasi, lulus)
            dTable.Columns.Add("Status");
            foreach (DataRow row in dTable.Rows)
            {
                if (row["mutation_date"] != DBNull.Value)
                    row["Status"] = string.Format("Mutasi ({0})", ((DateTime)row["mutation_date"]).ToShortDateString());
                else if (row["graduate_year"] != DBNull.Value)
                    row["Status"] = string.Format("Lulus ({0})", row["graduate_year"]);
                else
                    row["Status"] = "Masih terdaftar";
            }

            bindingSource1.DataSource = dTable;
            this.dataGridView1.DataSource = bindingSource1;

            //DataGridViewLinkColumn editColumn = new DataGridViewLinkColumn();
            //editColumn.UseColumnTextForLinkValue = true;
            //editColumn.Name = "Edit";
            //editColumn.Text = "Edit";
            //editColumn.HeaderText = "";
            //editColumn.ReadOnly = true;
            //editColumn.VisitedLinkColor = Color.Blue;
            //this.dataGridView1.Columns.Add(editColumn);

            //DataGridViewLinkColumn deleteColumn = new DataGridViewLinkColumn();
            //deleteColumn.UseColumnTextForLinkValue = true;
            //deleteColumn.Name = "Delete";
            //deleteColumn.HeaderText = "";
            //deleteColumn.Text = "Delete";
            //deleteColumn.ReadOnly = true;
            //deleteColumn.VisitedLinkColor = Color.Blue;
            //this.dataGridView1.Columns.Add(deleteColumn);

            this.dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;

            // Change column header name
            this.dataGridView1.Columns["stu_id"].HeaderText = "Nomor Induk";
            this.dataGridView1.Columns["stu_regdate"].HeaderText = "Tanggal Pendaftaran";
            this.dataGridView1.Columns["stu_name"].HeaderText = "Nama Anak";
            this.dataGridView1.Columns["stu_alias"].HeaderText = "Nama Pendek";
            this.dataGridView1.Columns["stu_gender"].HeaderText = "L/P";
            this.dataGridView1.Columns["stu_birthdate"].HeaderText = "Tanggal Lahir";
            this.dataGridView1.Columns["stu_birthplace"].HeaderText = "Tempat Lahir";
            this.dataGridView1.Columns["stu_regsession"].HeaderText = "Tahun Ajaran";
            this.dataGridView1.Columns["stu_desc"].HeaderText = "Keterangan";
            this.dataGridView1.Columns["stu_regform"].HeaderText = "Asal";

            // Set non displayed column
            this.dataGridView1.Columns["par_id"].Visible = false;
            this.dataGridView1.Columns["stu_image"].Visible = false;
            this.dataGridView1.Columns["mutation_reason"].Visible = false;
            this.dataGridView1.Columns["graduate_school"].Visible = false;
            this.dataGridView1.Columns["graduate_description"].Visible = false;
            this.dataGridView1.Columns["mutation_date"].Visible = false;
            this.dataGridView1.Columns["graduate_year"].Visible = false;

            this.dataGridView1.Columns["Status"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;

            this.dataGridView1.Refresh();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (this.add == null || this.add.IsDisposed)
            {
                add = new MuridAdd(this);
            }

            add.MdiParent = this.MdiParent;
            add.Show();
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (this.dataGridView1.Columns[e.ColumnIndex].Name == "Edit")
            {
                if (this.edit == null || this.edit.IsDisposed)
                    edit = new MuridEdit(this,
                        this.dataGridView1.Rows[e.RowIndex].Cells["stu_id"].Value.ToString(),
                        this.dataGridView1.Rows[e.RowIndex].Cells["stu_name"].Value.ToString(),
                        this.dataGridView1.Rows[e.RowIndex].Cells["stu_alias"].Value.ToString(),
                        this.dataGridView1.Rows[e.RowIndex].Cells["stu_gender"].Value.ToString(),
                        this.dataGridView1.Rows[e.RowIndex].Cells["stu_birthdate"].Value,
                        this.dataGridView1.Rows[e.RowIndex].Cells["stu_birthplace"].Value.ToString(),
                        this.dataGridView1.Rows[e.RowIndex].Cells["stu_regdate"].Value,
                        this.dataGridView1.Rows[e.RowIndex].Cells["stu_regsession"].Value.ToString(),
                        this.dataGridView1.Rows[e.RowIndex].Cells["stu_regform"].Value.ToString(),
                        this.dataGridView1.Rows[e.RowIndex].Cells["stu_desc"].Value.ToString(),
                        this.dataGridView1.Rows[e.RowIndex].Cells["par_id"].Value.ToString(),
                        this.dataGridView1.Rows[e.RowIndex].Cells["stu_image"].Value);


                 //check whether the form has been opened or not
                if (((Main)this.MdiParent).isOpenForm(edit))
                {
                    edit = null;
                    return;
                }

                this.edit.MdiParent = this.MdiParent;
                this.edit.Show();
                this.edit.Activate();

            }
            else if (this.dataGridView1.Columns[e.ColumnIndex].Name == "Delete")
            {
                var result = MessageBox.Show("Apakah Anda ingin menghapus murid tersebut ?", "Peringatan !", MessageBoxButtons.OKCancel);
                if (result == System.Windows.Forms.DialogResult.OK)
                {
                    DataTable dt = Database.getInstance().tes("select * from Student");
                    DataRow[] data = dt.Select("stu_id='" + this.dataGridView1.Rows[e.RowIndex].Cells["stu_id"].Value.ToString() + "'");

                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        if (dt.Rows[i].ItemArray[0].ToString() == data[0].ItemArray[0].ToString())
                        {
                            dt.Rows[i].Delete();
                            Database.getInstance().updateDB(dt);
                            this.dataGridView1.Rows.RemoveAt(e.RowIndex);
                            break;
                        }
                    }
                }
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.update();
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count < 1)
            {
                MessageBox.Show("Mohon pilih salah satu murid", "Perhatian!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            int idx = dataGridView1.CurrentRow.Index;

            if (this.edit == null || this.edit.IsDisposed)
                edit = new MuridEdit(this,
                    this.dataGridView1.Rows[idx].Cells["stu_id"].Value.ToString(),
                    this.dataGridView1.Rows[idx].Cells["stu_name"].Value.ToString(),
                    this.dataGridView1.Rows[idx].Cells["stu_alias"].Value.ToString(),
                    this.dataGridView1.Rows[idx].Cells["stu_gender"].Value.ToString(),
                    this.dataGridView1.Rows[idx].Cells["stu_birthdate"].Value,
                    this.dataGridView1.Rows[idx].Cells["stu_birthplace"].Value.ToString(),
                    this.dataGridView1.Rows[idx].Cells["stu_regdate"].Value,
                    this.dataGridView1.Rows[idx].Cells["stu_regsession"].Value.ToString(),
                    this.dataGridView1.Rows[idx].Cells["stu_regform"].Value.ToString(),
                    this.dataGridView1.Rows[idx].Cells["stu_desc"].Value.ToString(),
                    this.dataGridView1.Rows[idx].Cells["par_id"].Value.ToString(),
                    this.dataGridView1.Rows[idx].Cells["stu_image"].Value);


            //check whether the form has been opened or not
            if (((Main)this.MdiParent).isOpenForm(edit))
            {
                edit = null;
                return;
            }

            this.edit.MdiParent = this.MdiParent;
            this.edit.Show();
            this.edit.Activate();
        }

        private void btnHapus_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count < 1)
            {
                MessageBox.Show("Mohon pilih salah satu murid", "Perhatian!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            int idx = dataGridView1.CurrentRow.Index;

            var result = MessageBox.Show("Apakah Anda ingin menghapus murid tersebut ?", "Peringatan !", MessageBoxButtons.OKCancel);
            if (result == System.Windows.Forms.DialogResult.OK)
            {
                DataTable dt = Database.getInstance().tes("select * from Student");
                DataRow[] data = dt.Select("stu_id='" + this.dataGridView1.Rows[idx].Cells["stu_id"].Value.ToString() + "'");

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if (dt.Rows[i].ItemArray[0].ToString() == data[0].ItemArray[0].ToString())
                    {
                        dt.Rows[i].Delete();
                        Database.getInstance().updateDB(dt);
                        this.dataGridView1.Rows.RemoveAt(idx);
                        break;
                    }
                }
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count < 1)
            {
                MessageBox.Show("Mohon pilih salah satu murid", "Peringatan!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            DataGridViewRow row = dataGridView1.CurrentRow;
            if (row.Cells["Status"].Value.ToString() != "Masih terdaftar")
            {
                MessageBox.Show("Pilian ini hanya dapat bekerja pada murid dengan status terdaftar", "Peringatan!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            // Confirmation
            DialogResult ans = MessageBox.Show("Apakah Anda ingin melakukan mutasi terhadap murid tersebut?\nPerubahan yang terjadi tidak dapat dikembalikan seperti semula", "Perhatian!", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);
            if (ans == DialogResult.No) return;

            string id = row.Cells["stu_id"].Value.ToString();
            string name = row.Cells["stu_name"].Value.ToString();
            Mutasi mutasi = new Mutasi(id,name);
            DialogResult result = mutasi.ShowDialog(this);
            if (result == DialogResult.OK)
            {
                DateTime time = mutasi.MutationDate;
                string reason = mutasi.Reason;

                string sql = string.Format("UPDATE Student SET mutation_date = '{0}', mutation_reason = '{1}' WHERE stu_id = '{2}'", time.ToString("yyyy-MM-dd"), reason, id);
                Database.getInstance().nonquery(sql);

                MessageBox.Show("Murid bernama " + name + " (" + id + ") telah dimutasi", "Berhasil!", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.update();
            }
        }

        private void btnLulus_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count < 1)
            {
                MessageBox.Show("Mohon pilih salah satu murid", "Peringatan!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            DataGridViewRow row = dataGridView1.CurrentRow;
            if (row.Cells["Status"].Value.ToString() != "Masih terdaftar")
            {
                MessageBox.Show("Pilian ini hanya dapat bekerja pada murid dengan status terdaftar", "Peringatan!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            // Confirmation
            DialogResult ans = MessageBox.Show("Apakah Anda ingin meluluskan murid tersebut?\nPerubahan yang terjadi tidak dapat dikembalikan seperti semula", "Perhatian!", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);
            if (ans == DialogResult.No) return;

            string id = row.Cells["stu_id"].Value.ToString();
            string name = row.Cells["stu_name"].Value.ToString();
            Graduate graduate = new Graduate(id, name);
            DialogResult result = graduate.ShowDialog(this);
            if (result == DialogResult.OK)
            {
                string year = graduate.Year;
                string school = graduate.School;
                string description = graduate.Description;

                string sql = string.Format("UPDATE Student SET graduate_year = {0}, graduate_school = '{1}', graduate_description = '{2}' WHERE stu_id = '{3}'", new object[] {year, school, description, id});
                Database.getInstance().nonquery(sql);

                MessageBox.Show("Murid bernama " + name + " (" + id + ") telah lulus", "Berhasil!", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.update();
            }
        }

        private void btnCari_Click(object sender, EventArgs e)
        {
            MuridFilter muridfilter = new MuridFilter();
            DialogResult result = muridfilter.ShowDialog(this);
            if (result == DialogResult.OK)
            {
                string sql = muridfilter.SQL;
                //MessageBox.Show(sql);
                this.update(sql);
            }
        }
    }
}
